import React, { PropsWithChildren, useEffect } from 'react';

import { useAppDispatch } from '@/shared/store';
import { Router, useRouter } from 'next/router';

import { setRouter } from '../model';

/*
 сохраняет состояние роутера до перехода
*/

export const PrevRouterProvider = ({ children }: PropsWithChildren) => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  useEffect(() => {
    const onRouteChangeStart = () => {
      dispatch(setRouter({ asPath: router.asPath, pathname: router.pathname, query: router.query }));
    };
    Router.events.on('routeChangeStart', onRouteChangeStart);

    return () => {
      Router.events.off('routeChangeStart', onRouteChangeStart);
    };
  }, [router]);
  return <>{children}</>;
};
